<?php

namespace App\Http\Controllers\Admin;

use App\Models\NavigationArea;
use App\Models\NavigationPoint;
use App\Validate\NavigationPointValidate;
use Illuminate\Support\Facades\DB;

/**
 * 室内导航点位配置
 */
class NavigationPointController extends CommonController
{
    protected $model;
    protected $validate;

    public function __construct()
    {
        parent::__construct();

        $this->model = new NavigationPoint();
        $this->validate = new  NavigationPointValidate();
    }

    /**
     * 列表
     * @param page int 页码
     * @param limit int 分页大小
     * @param keywords string 搜索关键词
     */
    public function lists()
    {
        $page = $this->request->page ? intval($this->request->page) : 1;
        $limit = $this->request->limit ? intval($this->request->limit) : 10;
        $keywords = $this->request->keywords;
        $res = $this->model->lists($keywords, $limit);
        if (empty($res['data'])) {
            return $this->returnApi(203, "暂无数据");
        }
        $res = $this->disPageData($res);
        $res['data'] = $this->addSerialNumber($res['data'], $page, $limit);
        return $this->returnApi(200, "查询成功", true, $res);
    }

    /**
     * 详情
     * @param id int 点位id
     */
    public function detail()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('detail')->check($this->request->all())) {
            return $this->returnApi(201, $this->validate->getError());
        }

        $id = $this->request->id;
        $res = $this->model->where('id', $id)->first();
        if (!$res) {
            return $this->returnApi(201, "参数传递错误");
        }
        return $this->returnApi(200, "查询成功", true, $res->toArray());
    }

    /**
     * 新增
     * @param name string 点位名称
     * @param area_id int 所属区域
     * @param type 点位类型 1起点 2目的地 3过渡点 4起点/过渡点
     * @param img string 路线图  与line 2选一，若图片存在，则转换为 线路代码
     * @param line string 路线代码，路线图和路线代码传一个就行
     * @param transtion_area_id string 过渡区域id字符换，多个用,隔开
     */
    public function add()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('add')->check($this->request->all())) {
            return $this->returnApi(201, $this->validate->getError());
        }
        $name = $this->request->name;
        $area_id = $this->request->area_id;
        $type = $this->request->type;
        $img = $this->request->img;
        $line = $this->request->line;
        $transtion_area_id = $this->request->transtion_area_id; //过渡点
        //选择的区域是否存在
        $areaModel = new NavigationArea();
        $area_is_exists = $areaModel->nameIsExists($area_id, 'id');
        if (!$area_is_exists) return $this->returnApi(202, '所属区域不存在');

        $condition[] = ['area_id', '=', $this->request->area_id];
        $is_exists = $this->model->nameIsExists($name, 'name', null, 1, $condition);
        if ($is_exists) {
            return $this->returnApi(202, "该区域点位名称已存在");
        }
        if (in_array($type, [3, 4])) { //过渡点
            if (!$transtion_area_id) return $this->returnApi(202, '请选择过渡区域');
            //过渡区域是否都存在
            $transtion_area_ids = explode(',', $transtion_area_id);
            if (in_array($area_id, $transtion_area_ids)) return $this->returnApi(202, '过渡区域不能包含当前区域');
            $point_area_count = $areaModel->where('is_del', 1)
                ->where('is_play', 1)
                ->whereIn('id', $transtion_area_ids)
                ->count();
            if ($point_area_count != count($transtion_area_ids)) {
                return $this->returnApi(202, '过渡区域参数错误');
            }
        }

        //如果传的线路图片，则转为代码储存
        if (!empty($img)) {
            //查看img格式是否正确
            $check_img = $areaModel->checkSvgImg($img);
            if ($check_img['code'] != 200) return $this->returnApi(202, $check_img['msg']);
            $line = $this->model->getLineByImg($img);
            //同时删除svg图片，减少服务器储存压力
            $this->deleteFile($img);
        }
        $data = [
            'name' => $name,
            'area_id' => $area_id,
            'line' => $line,
            'type' => $type,
            'transtion_area_id' => $transtion_area_id,
        ];
        $res = $this->model->add($data);
        if (!$res) {
            return $this->returnApi(202, "新增失败");
        }
        return $this->returnApi(200, "新增成功", true);
    }

    /**
     * 编辑
     * @param id int 点位ID
     * @param name string 点位名称
     * @param area_id int 所属区域
     * @param type 点位类型  1起点 2目的地 3过渡点 4起点/过渡点
     * @param img string 路线图  与line 2选一，若图片存在，则转换为 线路代码
     * @param line string 路线代码，路线图和路线代码传一个就行
     * @param transtion_area_id  string 过渡区域id字符换，多个用,隔开
     */
    public function change()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('change')->check($this->request->all())) {
            return $this->returnApi(201, $this->validate->getError());
        }
        $id = $this->request->id;
        $name = $this->request->name;
        $area_id = $this->request->area_id;
        $type = $this->request->type;
        $img = $this->request->img;
        $line = $this->request->line;
        $transtion_area_id = $this->request->transtion_area_id; //过渡点

        $data = $this->model->where('id', $id)->first();
        if (!$data) {
            return $this->returnApi(201, "参数传递错误");
        }

        $areaModel = new NavigationArea();
        $area_is_exists = $areaModel->nameIsExists($area_id, 'id');
        if (!$area_is_exists) return $this->returnApi(202, '所属区域不存在');
        
        $condition[] = ['area_id', '=', $this->request->area_id];
        $is_exists = $this->model->nameIsExists($name, 'name', $this->request->id, 1, $condition);
        if ($is_exists) {
            return $this->returnApi(202, "该区域点位名称已存在");
        }

        if (in_array($type, [3, 4])) { //过渡点
            if (!$transtion_area_id) return $this->returnApi(202, '请选择过渡区域');
            //过渡区域是否都存在
            $transtion_area_ids = explode(',', $transtion_area_id);
            $point_area_count = $areaModel->where('is_del', 1)->whereIn('id', $transtion_area_ids)->count();
            if ($point_area_count != count($transtion_area_ids)) {
                return $this->returnApi(202, '过渡区域参数错误');
            }
        }

        //如果传的线路图片，则转为代码储存
        if (!empty($img)) {
            //查看img格式是否正确
            $check_img = $areaModel->checkSvgImg($img);
            if ($check_img['code'] != 200) return $this->returnApi(202, $check_img['msg']);
            $line = $this->model->getLineByImg($img);
            //同时删除svg图片，减少服务器储存压力
            $this->deleteFile($img);
        }
        // 启动事务
        DB::beginTransaction();
        try {
            $data = [
                'id' => $id,
                'name' => $name,
                'area_id' => $area_id,
                'line' => $line,
                'type' => $type,
                'transtion_area_id' => $transtion_area_id,
            ];
            $this->model->change($data);
            // 提交事务
            DB::commit();
            return $this->returnApi(200, "保存成功", true);
        } catch (\Exception $e) {
            // 回滚事务
            DB::rollBack();
            return $this->returnApi(202, $e->getMessage());
        }
    }

    /**
     * 删除
     * @param id int 点位id
     */
    public function del()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('del')->check($this->request->all())) {
            return $this->returnApi(201, $this->validate->getError());
        }
        $res = $this->model->del($this->request->id);
        if ($res) {
            return $this->returnApi(200, "删除成功", true);
        }
        return $this->returnApi(202, $res);
    }

    /**
     * 发布与取消发布
     * @param ids 点位id，多个用逗号拼接   all 是，其余字符  ids 必传
     * @param is_play 是否发布  1.发布  2.未发布  默认2
     */
    public function playAndCancel()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('play_and_cancel')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }

        list($code, $msg) = $this->model->resumeAndCancel($this->request->ids, 'is_play', $this->request->is_play);

        $is_play = $this->request->is_play == 1 ? '发布' : '取消发布';
        if ($code === 200) {
            return $this->returnApi(200, $is_play . $msg, true);
        }
        return $this->returnApi($code, $is_play . $msg);
    }

    /**
     * 修改区域排序
     * content json格式数据  [{"id":1,"sort":2},{"id":2,"sort":2},{"id":3,"sort":3},{"id":4,"sort":4},{"id":5,"sort":5}]   第一个 sort 最大
     */
    public function sortChange()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('sort_change')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }

        $content = $this->request->input('content', '');
        if (empty($content)) {
            return $this->returnApi(201, "参数传递错误");
        }
        $content = json_decode($content, true);

        DB::beginTransaction();
        try {
            foreach ($content as $key => $val) {
                $this->model->where('id', $val['id'])->update(['sort' => $val['sort']]);
            }
            DB::commit();
            return $this->returnApi(200, "修改成功", true);
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->returnApi(202, $e->getMessage());
        }
    }
}
